package cn.sightsnow.zh.service;

import cn.sightsnow.zh.entity.Location;
import cn.sightsnow.zh.entity.Route;
import cn.sightsnow.zh.entity.Target;
import cn.sightsnow.zh.repository.LocationRepository;
import cn.sightsnow.zh.repository.RouteRepository;
import cn.sightsnow.zh.repository.TargetRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;

//@RequiredArgsConstructor
@Service
@Slf4j
public class TrackService {
    private final LocationRepository locationRepository;
    private final RouteRepository routeRepository;
    private final TargetRepository targetRepository;

    public TrackService(
            LocationRepository locationRepository,
            RouteRepository routeRepository,
            TargetRepository targetRepository
    ) {
        this.locationRepository = locationRepository;
        this.routeRepository = routeRepository;
        this.targetRepository = targetRepository;
    }

    public Page<Location> findLocationByTargetId(String targetId, String routeId, Pageable pageable) {
        if (targetId != null && routeId != null) {
            return locationRepository.findByTargetIdAndRouteId(targetId, routeId, pageable);
        } else if (targetId != null) {
            return locationRepository.findByTargetId(targetId, pageable);
        } else if (routeId != null) {
            return locationRepository.findByRouteId(routeId, pageable);
        } else {
            return locationRepository.findAll(pageable);
        }
    }

    /**
     * 添加定位信息到数据库
     *
     * @param location
     */
    public void insertLocation(Location location) {
        //根据设备ID 查找 Optional是容器类，代表一个值存在或不存在
        Optional<Target> targetOptional = targetRepository.findById(location.getTargetId());
        //如果设备不存在，抛出异常
        if (!targetOptional.isPresent()) {
            log.info("未找到ID为：{}的设备", location.getTargetId());
            throw new RuntimeException("TrackedTarget Not Found");
        }
        //获取容器中的值
        Target target = targetOptional.get();
        target.setUpdateTime(new Date());
        targetRepository.save(target);
        //根据路线ID 查找
        Optional<Route> routeOptional = routeRepository.findById(location.getRouteId());
        if (!routeOptional.isPresent()) {
            log.info("未找到ID为：{}的路线", location.getRouteId());
            throw new RuntimeException("Route Not Found");
        }

        //Route route = routeOptional.get();
        //if (route.getData() != null) {}

        locationRepository.insert(location);
    }
}
